package cn.com.darly.vpm.mobile;

import cn.com.darly.vpm.business.BusinessApi;
import cn.com.darly.vpm.business.amuse.bean.Amuse;
import cn.com.darly.vpm.business.friend.bean.FriendShip;
import cn.com.darly.vpm.framework.common.DateUtil;
import cn.com.darly.vpm.framework.common.StringDiyUtils;
import cn.com.darly.vpm.framework.common.UuidGenerateUtil;
import cn.com.darly.vpm.mobile.cfg.MobileBaseController;
import cn.com.darly.vpm.mobile.session.SessionUtil;
import cn.com.darly.vpm.security.securitycfg.SecurityApi;
import cn.com.darly.vpm.security.user.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户登录完成后，获取的用户关联信息类，包括获取用户好友。用户好友信息
 * @author Darly/张宇辉/2018/5/8 10:21
 * @version 1.0/cn.com.darly.vpm.mobile
 */
@Controller
@RequestMapping("mobile/user")
public class LoginUserController extends MobileBaseController {

    @Resource
    BusinessApi businessApi;

    @Autowired
    SecurityApi api;

    /**
     * @return 新用户注册接口
     */
    @RequestMapping(value = {"/searchuser"}, method = RequestMethod.POST)
    public void indexSearchuser(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String  usertoken  = request.getHeader("usertoken");
        if (StringDiyUtils.isEmpty(usertoken)||StringDiyUtils.isEmpty(username)){
            simpleResult("201","参数缺失",request,response);
            return;
        }
        //获取用户登录信息
        User data = SessionUtil.SESSION_MAP.get(usertoken);
        if (data==null) {
            simpleResult("204","用户登录失效，请登录后重试",request,response);
            return;
        }
        List<User> users = api.findUserLikeName(username);
        if (users!=null){
            for (User us:users) {
                int up = businessApi.isConnectFriendShip(data.getId(),us.getId());
                us.setFriendup(up);
            }
            dataResult("200","查询成功",users,request,response);
        }else {
            simpleResult("201","没有匹配用户",request,response);
        }
    }


    /**
     * @return 查找用戶好友接口
     */
    @RequestMapping(value = {"/friendship"}, method = RequestMethod.POST)
    public void friendship(HttpServletRequest request, HttpServletResponse response){
       String  usertoken  = request.getHeader("usertoken");
        if (StringDiyUtils.isEmpty(usertoken)){
            simpleResult("201","参数缺失",request,response);
            return;
        }
        //获取用户登录信息
        User data = SessionUtil.SESSION_MAP.get(usertoken);
        if (data==null) {
            simpleResult("204","用户登录失效，请登录后重试",request,response);
            return;
        }
        //获取登录用户的ID，根据id进行查询好友
        List<FriendShip> users =  businessApi.userFriend(data.getId());
        if (users != null){
            List<User> friendship= new ArrayList<User>();
            for (FriendShip ship:users) {
                User friend = api.findUserById(ship.getFriendid());
                friendship.add(friend);
            }
            if (friendship!=null&&friendship.size()>0){
                dataResult("200", "查询成功", friendship, request, response);
            }else {
                simpleResult("201","没有好友，请添加好友",request,response);
            }
        }else {
            simpleResult("201","查询失败，服务端异常",request,response);

        }
    }


    /**
     * @return 好友申请接口，收到后，推送消息到盆友
     */
    @RequestMapping(value = {"/applyfriend"}, method = RequestMethod.POST)
    public void addfriend(HttpServletRequest request, HttpServletResponse response){
        String browser =findBrowser(request);

        String  usertoken  = request.getHeader("usertoken");
        String  userid  = request.getParameter("userid");
        String  apply  = request.getParameter("apply");
        String  nickname  = request.getParameter("nickname");
        if (StringDiyUtils.isEmpty(usertoken)||StringDiyUtils.isEmpty(userid)||StringDiyUtils.isEmpty(apply)||StringDiyUtils.isEmpty(nickname)){
            simpleResult("201","参数缺失",request,response);
            return;
        }
        //获取用户登录信息
        User data = SessionUtil.SESSION_MAP.get(usertoken);
        if (data==null) {
            simpleResult("204","用户登录失效，请登录后重试",request,response);
            return;
        }
        //增加好友
        if (data.getId().equals(userid)){
            //登录用户和自己不能添加好友
            simpleResult("204","无法添加本人为好友",request,response);
            return;
        }

        FriendShip shiper = new FriendShip();
        shiper.setId(UuidGenerateUtil.getUUIDLong());
        shiper.setUserid(data.getId());
        shiper.setFriendid(userid);
        shiper.setCreateby(data.getName());
        shiper.setCreatetime(DateUtil.now());
        shiper.setUpdateby(data.getName());
        shiper.setUpdatetime(DateUtil.now());
        shiper.setFriendup("0");
        shiper.setFriendnickname(nickname);
        shiper.setBackup(apply);
        FriendShip ship = businessApi.userNewFriend(shiper);
        if (ship!=null) {
            saveLog(data.getId(),"0",0,3,data.getName(),browser,"[手机用户："+data.getName()+"申请"+ship.getName()+"添加为好友]");
            publishMessage("1#用户："+data.getName()+"申请添加您为好友！",ship.getFrienddeviceId());
            logger.info("[发送给："+"vpm@"+ship.getFrienddeviceId()+"好友申请消息]");
            dataResult("200", "好友申请成功", ship, request, response);

        }else {
            simpleResult("200","添加失败",request,response);
        }
    }


    /**
     * @return 申請的好友列表（用户被其他人申请好友，和用戶自己申請的好友集合）
     */
    @RequestMapping(value = {"/applyer"}, method = RequestMethod.POST)
    public void applyer(HttpServletRequest request, HttpServletResponse response){
        String  usertoken  = request.getHeader("usertoken");
        if (StringDiyUtils.isEmpty(usertoken)){
            simpleResult("201","参数错误",request,response);
            return;
        }
        //获取用户登录信息
        User data = SessionUtil.SESSION_MAP.get(usertoken);
        if (data==null) {
            simpleResult("204","用户登录失效，请登录后重试",request,response);
            return;
        }
        List<FriendShip> users = businessApi.findUserListById(data.getId());
        if (users!=null){
            dataResult("200","查询成功",users,request,response);
        }else {
            simpleResult("201","没有匹配用户",request,response);
        }
    }


    /**
     * @return 同意好友申请，修改数据库，并成为朋友
     */
    @RequestMapping(value = {"/viaapply"}, method = RequestMethod.POST)
    public void viaapply(HttpServletRequest request, HttpServletResponse response){
        String browser =findBrowser(request);

        String  usertoken  = request.getHeader("usertoken");
        String friendId = request.getParameter("friendId");

        if (StringDiyUtils.isEmpty(usertoken)||StringDiyUtils.isEmpty(friendId)){
            simpleResult("201","参数错误",request,response);
            return;
        }
        //获取用户登录信息
        User data = SessionUtil.SESSION_MAP.get(usertoken);
        if (data==null) {
            simpleResult("204","用户登录失效，请登录后重试",request,response);
            return;
        }

        User friend = api.findUserById(friendId);
        if (friend == null){
            simpleResult("201","用户不存在，数据库异常",request,response);
            return;
        }
        //通过用户ID和好友ID，定位两条信息。并对其两条信息进行修改。
        boolean isFriend = businessApi.passThrou(data.getId(),friendId);
        if (isFriend){
            saveLog(data.getId(),"0",0,3,data.getName(),browser,"[手机用户："+data.getName()+"同意"+friend.getName()+"的申请]");
            publishMessage("2#用户："+data.getName()+"同意您的好友申请",friend.getDeviceId());
            logger.info("[发送给："+"vpm@"+friend.getDeviceId()+"同意您的好友申请]");

            dataResult("200","通过好友验证",isFriend,request,response);
        }else {
            simpleResult("201","好友验证失败",request,response);
        }
    }



    /**
     * @return 用戶發佈話題接口
     */
    @RequestMapping(value = {"/publishamuse"}, method = RequestMethod.POST)
    public void publishamuse(HttpServletRequest request, HttpServletResponse response){
        String browser =findBrowser(request);
        String  usertoken  = request.getHeader("usertoken");
        String title = request.getParameter("title");
        String content = request.getParameter("content");

        if (StringDiyUtils.isEmpty(usertoken)||StringDiyUtils.isEmpty(title)||StringDiyUtils.isEmpty(content)){
            simpleResult("201","参数错误",request,response);
            return;
        }
        //获取用户登录信息
        User data = SessionUtil.SESSION_MAP.get(usertoken);
        if (data==null) {
            simpleResult("204","用户登录失效，请登录后重试",request,response);
            return;
        }
        //在这里封装话题
        Amuse amuse = new Amuse();
        amuse.setId(UuidGenerateUtil.getUUIDLong());
        amuse.setAuthor(data.getId());
        amuse.setTitle(title);
        amuse.setContent(content);
        amuse.setWatch(0);
        amuse.setComment(0);
        amuse.setCreateby(data.getId());
        amuse.setCteatetime(DateUtil.now());
        amuse.setUpdateby(data.getId());
        amuse.setUpdatetime(DateUtil.now());
        amuse.setStatus(0);
        boolean isp  = businessApi.publish(amuse);

        if (isp){
            //添加成功
            saveLog(data.getId(),"0",0,3,data.getName(),browser,"[手机用户："+data.getName()+"发布新话题]");
            dataResult("200","添加成功，请等待审核",true,request,response);
        }else {
            //添加失败
            simpleResult("201","添加话题失败",request,response);
        }

    }
    /**
     * @return 用戶查詢自己已發佈話題接口
     */
    @RequestMapping(value = {"/publishedamuse"}, method = RequestMethod.POST)
    public void publishedamuse(HttpServletRequest request, HttpServletResponse response){
        String  usertoken  = request.getHeader("usertoken");
        if (StringDiyUtils.isEmpty(usertoken)){
            simpleResult("201","参数错误",request,response);
            return;
        }
        //获取用户登录信息
        User data = SessionUtil.SESSION_MAP.get(usertoken);
        if (data==null) {
            simpleResult("204","用户登录失效，请登录后重试",request,response);
            return;
        }
        List<Amuse> amuses = businessApi.published(data.getId());
        if (amuses!=null){
            for (Amuse amus:amuses) {
                amus.setUser(api.findUserById(data.getId()));
            }
            dataResult("200","查詢成功",amuses,request,response);
        }else {
            simpleResult("201","没有发布过话题",request,response);
        }

    }

}
